package org.code.mallspringboot.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.code.mallspringboot.mapper.MemberMapper;
import org.code.mallspringboot.pojo.UmsMember;
import org.code.mallspringboot.service.UmsRoleService;
import org.code.mallspringboot.service.impl.MemberServiceImpl;
import org.code.mallspringboot.service.impl.UmsAdminServiceImpl;
import org.code.mallspringboot.utils.JwtUtil;
import org.code.mallspringboot.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sso")
public class UserController {


    @Autowired
    private MemberServiceImpl memberService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private UmsAdminServiceImpl adminService;

    @Autowired
    private UmsRoleService roleService;

    @Autowired
    private MemberMapper memberMapper;

    @PostMapping("/login")
    public CommonResult login(String username,String password){

        UmsMember umsMember = (UmsMember) memberService.loadUserByUsername(username);
        if (!passwordEncoder.matches(password,umsMember.getPassword())){
            return CommonResult.failed("密码错误!");
        }

        String token = JwtUtil.createToken(umsMember.getUsername());
        Map<String,Object> map = new HashMap<>();
        map.put("tokenHead", tokenHead);
        map.put("token" , token);
        return CommonResult.success(map);
    }

    @GetMapping(value = "/info")
    public CommonResult getAdminInfo(Principal principal) {
//        if(null == principal){
//            return CommonResult.unauthorized(null);
//        }
//        String username = principal.getName();
//        UmsMember umsMember = memberMapper.loadUserByUsername(username);
////        UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
//        Map<String, Object> data = new HashMap<>();
//        data.put("username", umsMember.getUsername());
//        // 获取用户菜单权限
//        data.put("menus", roleService.getMenuList(umsMember.getId()));
//        // 获取用户头像
//        data.put("icon", umsMember.getIcon());
//        // 获取用户角色
//        List<UmsRole> roleList = adminService.getRoleList(umsMember.getId());
//        if(CollUtil.isNotEmpty(roleList)){
//            List<String> roles = roleList.stream().map(UmsRole::getName).collect(Collectors.toList());
//            data.put("roles",roles);
//        }
        return CommonResult.success(null);
    }

}
